(function (w) {
  //herry对象
  w.herry = {};
  //iframe的id
  if(!herry.iframeId) {
    herry.iframeId = 'iframe'
  }
  //父窗口名字
  if(!herry.parentName) {
    herry.parentName = '父窗口'
  }
  //子窗口名字
  if(!herry.childName) {
    herry.childName = '子窗口'
  }
  //跨域对象
  const messageObj = {};
  //父页面
  /**
   * 发送给子页面数据
   */
  const postMessage = (data, fn = null) => {
    const iframe = document.getElementById(herry.iframeId)
    iframe.contentWindow.postMessage(
      {
        name: herry.parentName, //父页面名字
        ...data,
      },
      "*"
    );
    messageObj[data.action] = fn;
  };
  /**
   * 监听子页面返回的数据
   */
   w.addEventListener(
    "message",
    (event) => {
      const { data } = event;
      if (data && typeof data === "object" && data.name === herry.childName) {
        messageObj[data.action](data);
      }
    },
    false
  );
  //子页面
  /**
   * 返回数据给父页面 参1=当前action 参2=返回的数据
   */
  const returnData = (action, data) => {
    top.postMessage(
      {
        name: herry.childName, //子页面名字
        action,
        data,
      },
      "*"
    );
  };
  /**
   * 监听父页面发送的数据
   */
   w.addEventListener(
    "message",
    async (event) => {
      const { data } = event;
      if (data && typeof data === "object" && data.name === herry.parentName) {
        if (herry.callback) {
          herry.callback(data)
        }
      }
    },
    false
  );
  herry.postMessage = postMessage;
  herry.returnData = returnData;
})(window);
